package cn.suxiaoxiang.suwebverify.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * SQLiteDownloader - 自动下载SQLITE驱动程序（优化版，使用HttpURLConnection）
 */
public class SQLiteDownloader {

    // 使用国内阿里云镜像加速
    private static final String SQLITE_URL = "https://maven.aliyun.com/repository/public/org/xerial/sqlite-jdbc/3.42.0.0/sqlite-jdbc-3.42.0.0.jar";

    // 网络参数配置
    private static final int CONNECT_TIMEOUT = 8000;     // 8秒连接超时
    private static final int READ_TIMEOUT = 20000;       // 20秒读取超时
    private static final int BUFFER_SIZE = 64 * 1024;    // 64KB缓冲区
    private static final int MAX_RETRIES = 3;            // 最大重试次数
    private static final int RETRY_DELAY = 1500;         // 重试间隔(毫秒)
    private static final long MIN_FILE_SIZE = 3_000_000; // 最小文件大小3MB

    public static void ensureDriver(File pluginFolder) {
        File libDir = new File(pluginFolder, "lib");
        if (!libDir.exists() && !libDir.mkdirs()) {
            System.err.println("[SuWebVerify] 无法创建lib目录");
            return;
        }

        File sqliteJar = new File(libDir, "sqlite-jdbc.jar");

        if (!sqliteJar.exists()) {
            System.out.println("[SuWebVerify] 开始下载SQLite驱动 (镜像源：阿里云)...");

            int retryCount = 0;
            boolean success = false;
            long totalBytes = 0;
            long startTime = System.currentTimeMillis();

            download:
            while (retryCount < MAX_RETRIES && !success) {
                try {
                    // 使用HttpURLConnection进行文件下载
                    HttpURLConnection connection = (HttpURLConnection) new URL(SQLITE_URL).openConnection();
                    connection.setConnectTimeout(CONNECT_TIMEOUT);
                    connection.setReadTimeout(READ_TIMEOUT);

                    try (InputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE);
                         OutputStream out = new BufferedOutputStream(new FileOutputStream(sqliteJar), BUFFER_SIZE)) {

                        byte[] buffer = new byte[BUFFER_SIZE];
                        int bytesRead;
                        long lastPrintTime = 0;

                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                            totalBytes += bytesRead;

                            // 每1秒打印带速度的进度
                            long currentTime = System.currentTimeMillis();
                            if (currentTime - lastPrintTime > 1000) {
                                double speed = (totalBytes / 1024.0) / ((currentTime - startTime) / 1000.0);
                                System.out.printf(
                                        "[SuWebVerify] 进度: %.2fMB | 速度: %.1fKB/s%n",
                                        totalBytes / (1024.0 * 1024),
                                        speed
                                );
                                lastPrintTime = currentTime;
                            }
                        }

                        // 基础文件校验
                        if (sqliteJar.length() < MIN_FILE_SIZE) {
                            throw new IOException("文件不完整，大小异常: " +
                                    sqliteJar.length() + "字节");
                        }

                        // 统计最终速度
                        double totalTime = (System.currentTimeMillis() - startTime) / 1000.0;
                        System.out.printf(
                                "[SuWebVerify] 下载成功! 大小: %.2fMB | 耗时: %.1fs | 均速: %.1fKB/s%n",
                                totalBytes / (1024.0 * 1024),
                                totalTime,
                                (totalBytes / 1024.0) / totalTime
                        );
                        success = true;
                    }
                } catch (SocketTimeoutException ste) {
                    handleRetry(++retryCount, "网络超时");
                } catch (IOException ioe) {
                    handleRetry(++retryCount, "传输错误: " + ioe.getMessage());
                }

                // 重试前等待
                if (!success && retryCount < MAX_RETRIES) {
                    try {
                        Thread.sleep(RETRY_DELAY);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                }
            }

            if (!success) {
                System.err.println(
                        "[SuWebVerify] 下载失败，请:\n" +
                                "1. 检查网络连接\n" +
                                "2. 尝试手动下载: " + SQLITE_URL + "\n" +
                                "3. 检查磁盘权限"
                );
                return;
            }
        }

        // 加载驱动到ClassLoader
        try {
            URL jarUrl = sqliteJar.toURI().toURL();
            URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            // 检查是否已加载
            for (URL url : sysLoader.getURLs()) {
                if (url.sameFile(jarUrl)) {
                    System.out.println("[SuWebVerify] 驱动已加载");
                    return;
                }
            }

            // 反射添加URL
            java.lang.reflect.Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(sysLoader, jarUrl);
            System.out.println("[SuWebVerify] 驱动加载成功");
        } catch (Exception e) {
            System.err.println("[SuWebVerify] 驱动加载失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 统一重试处理
    private static void handleRetry(int retryCount, String reason) {
        System.err.printf(
                "[SuWebVerify] %s (重试 %d/%d)%n",
                reason,
                retryCount,
                MAX_RETRIES
        );
    }
}
